<template>
  <div>
    <van-nav-bar title="项目" left-arrow @click-left="onClickLeft" />
    <h2 style="text-align: left;padding-left: 15px;">{{assetsObj.assetsName}}</h2>
    <div class="van-cell van-field">
      <div class="van-cell__title van-field__label">
        <span>一级分类</span>
      </div>
      <div class="van-cell__value">
        <div class="van-field__body">
          <div class="van-field__control">{{assetsObj.level1}}</div>
        </div>
      </div>
    </div>
    <div v-for="(item, i) in photo1" :key="item.label + i">
      <!-- <van-field :value="item.label" label="照片描述" placeholder="请输入照片描述" /> -->
      <van-swipe-cell :right-width="60">
        <div class="van-cell van-field" style="margin-bottom: 10px;">
          <div class="van-cell__title van-field__label">
            <span>照片描述</span>
          </div>
          <div class="van-cell__value">
            <div class="van-field__body">
              <input :value="item.label" :data-i="i" @change="onInputChange1" type="text" class="van-field__control" placeholder="请输入照片描述" />
            </div>
          </div>
        </div>
        <van-button square slot="right" type="danger" text="删除" @click="delPhoto1(i)" />
      </van-swipe-cell>
      <van-uploader multiple :after-read="afterRead1" :max-size="maxSize" @oversize="oversize" :name="i + ''">
        <div class="van-uploader__wrapper">
          <div class="van-image van-uploader__preview van-image-zindex"
            v-for="(item1,index) in item.list"
            :key="item1.src + index"
            @click.stop.prevent="imgClick(item1.src, item.list)"
          >
            <img :src="item1.src" class="van-image__img" style="object-fit: cover;">
            <van-icon name="clear" @click.stop.prevent="delImg1(i, item1, item.list)" />
          </div>
          <div class="van-image van-uploader__preview" style="border: 1px dashed #e5e5e5;text-align:center;line-height:80px;">
            <van-icon name="plus" />
          </div>
        </div>
      </van-uploader>
    </div>
    <div class="button-wrap">
      <van-button type="primary" @click="addPhoto1" style="margin-right:10px;">添加照片</van-button>
      <van-button type="primary" @click="save1()">保存</van-button>
    </div>
    <div class="van-cell van-field">
      <div class="van-cell__title van-field__label">
        <span>二级分类</span>
      </div>
      <div class="van-cell__value" @click="showSheet = true">
        <div class="van-field__body" v-if="level2Obj.label">
          <div class="van-field__control">{{level2Obj.label || ''}}</div>
          <div class="van-field__right-icon">
            <i class="van-icon van-icon-arrow-down"></i>
          </div>
        </div>
        <div class="van-field__body" v-else>
          <div class="van-field__control">
            <van-button type="primary" size="small" @click.stop="goToLevel2()">添加二级分类</van-button>
          </div>
        </div>
      </div>
    </div>
    <div v-for="(item, i) in photo2" :key="item.label + i">
      <van-swipe-cell :right-width="60">
        <div class="van-cell van-field" style="margin-bottom: 10px;">
          <div class="van-cell__title van-field__label">
            <span>照片描述</span>
          </div>
          <div class="van-cell__value">
            <div class="van-field__body">
              <input :value="item.label" :data-i="i" @change="onInputChange2" type="text" class="van-field__control" placeholder="请输入照片描述" />
            </div>
          </div>
        </div>
        <van-button square slot="right" type="danger" text="删除" @click="delPhoto2(i)" />
      </van-swipe-cell>
      <van-uploader multiple :after-read="afterRead2" :max-size="maxSize" @oversize="oversize" :name="i + ''">
        <div class="van-uploader__wrapper">
          <div class="van-image van-uploader__preview van-image-zindex"
            v-for="(item1,index) in item.list"
            :key="item1.src + index + '-' + i"
            @click.stop.prevent="imgClick(item1.src, item.list)"
          >
            <img :src="item1.src" class="van-image__img" style="object-fit: cover;">
            <van-icon name="clear" @click.stop.prevent="delImg2(i, item1, item.list)" />
          </div>
          <div class="van-image van-uploader__preview" style="border: 1px dashed #e5e5e5;text-align:center;line-height:80px;">
            <van-icon name="plus" />
          </div>
        </div>
      </van-uploader>
    </div>
    <div class="button-wrap" v-if="level2Obj.label">
      <van-button type="primary" @click="addPhoto2" style="margin-right:10px;">添加照片</van-button>
      <van-button type="primary" @click="save2()">保存</van-button>
    </div>
    <div class="button-wrap">
      <van-button style="width:90%" type="primary" @click="goToExport">导出</van-button>
    </div>
    <van-action-sheet v-model="showSheet" :actions="actions" @select="onSelect"/>
  </div>
</template>
<script>
import { getTaskList, getLevel1List, saveLevel1Photo, saveLevel2Photo } from "@/utils/storage.js";
import { compressImageCanvas } from "@/utils/file.js";

import vanNavBar from "vant/lib/nav-bar";
import "vant/lib/nav-bar/style";
import vanActionSheet from "vant/lib/actionsheet";
import "vant/lib/actionsheet/style";
import vanButton from "vant/lib/button";
import "vant/lib/button/style";
import vanSwipeCell from "vant/lib/swipe-cell";
import "vant/lib/swipe-cell/style";
import vanIcon from "vant/lib/icon";
import "vant/lib/icon/style";
import "vant/lib/field/style";
import vanUploader from "vant/lib/uploader";
import "vant/lib/uploader/style";
export default {
  components: {
    vanNavBar,
    vanActionSheet,
    vanButton,
    vanIcon,
    vanUploader,
    vanSwipeCell
  },
  data() {
    return {
      maxSize: 6 * 1024 * 1024,
      assetsObj: {},
      showSheet: false,
      tasklist: [],
      actions: [],
      level2Index: 0,
      photo1: [],
      photo2: [],
    };
  },
  computed: {
    level2Obj() {
      return this.assetsObj && this.assetsObj.level2list ? this.assetsObj.level2list[this.level2Index] || {} : {}
    }
  },
  created() {
    const i = parseInt(this.$route.params.i) || 0;
    this.tasklist = getTaskList();
    this.assetsObj = this.tasklist[i] || null;
    if (this.assetsObj && this.assetsObj.level2list && this.assetsObj.level2list.length > 0) {
      this.actions = this.assetsObj.level2list.map((t, i) => {
        return {
          ...t,
          i,
          name: t.label
        };
      });
    }
    
    let photo1 = this.assetsObj.photo || [];
    this.photo1 = photo1.map((p) => {
      return {
        label: p.label,
        list: (p.list || []).map((l) => {
          return {
            item: l.item,
            src: localStorage.getItem(l.item)
          }
        })
      }
    });
    let photo2 = this.level2Obj.photo || [];
    this.photo2 = photo2.map((p) => {
      return {
        label: p.label,
        list: (p.list || []).map((l) => {
          return {
            item: l.item,
            src: localStorage.getItem(l.item)
          }
        })
      }
    });
  },
  methods: {
    oversize() {
      this.$toast('请上传小于6M大小的图片');
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    onSelect(obj) {
      this.showSheet = false;
      this.level2Index = Number(obj.i);
      const level2list = this.assetsObj.level2list ? this.assetsObj.level2list : [];
      const level2Obj = level2list[this.level2Index] || {};
      const photo2 = level2Obj.photo || [];
      this.photo2 = photo2.map((p) => {
        return {
          label: p.label,
          list: (p.list || []).map((l) => {
            return {
              item: l.item,
              src: localStorage.getItem(l.item)
            }
          })
        }
      });
    },
    goToLevel2() {
      const label = this.assetsObj.level1;
      const level1List = getLevel1List();
      for(let i = 0; i < level1List.length; i++) {
        if (level1List[i].label === label) {
          this.$router.push(`/layout/level2Add/${i}`);
        }
      }
    },
    goToExport() {
      const tasklist = getTaskList();
      for(let i = 0; i < tasklist.length; i++) {
        if (tasklist[i].assetsName === this.assetsObj.assetsName) {
          this.$router.push(`/layout/export/${i}`);
        }
      }
    },
    imgClick(src, list) {
      const arr = list.map(t => t.src);
      const i = arr.findIndex(t => t === src);
      this.$imagePreview({
        images: arr,
        startPosition: i,
        onClose() {
          // do something
        }
      });
    },
    onInputChange1(e) {
      const index = Number(e.target.dataset.i);
      this.photo1[index].label = e.target.value;
    },
    onInputChange2(e) {
      const index = Number(e.target.dataset.i);
      this.photo2[index].label = e.target.value;
    },
    delImg1(index, item, list) {
      const i = list.findIndex(t => t.src === item.src);
      let arr = this.photo1[index].list;
      arr.splice(i, 1);
      this.photo1[index].list = arr;
      this.save1(() => {
        localStorage.removeItem(item.item);
      });
    },
    delImg2(index, item, list) {
      const i = list.findIndex(t => t.src === item.src);
      let arr = this.photo2[index].list;
      arr.splice(i, 1);
      this.photo2[index].list = arr;
      this.save2(() => {
        localStorage.removeItem(item.item);
      });
    },
    addPhoto1() {
      this.photo1.push({
        label: '',
        list: []
      });
    },
    addPhoto2() {
      this.photo2.push({
        label: '',
        list: []
      });
    },
    delPhoto1(i) {
      this.$dialog.confirm({
        title: '删除确认',
        message: '是否确定删除该照片描述？'
      }).then(() => {
        const obj = {...this.photo1[i]};
        const list = obj.list || [];
        this.photo1 = this.photo1.filter((t,index) => { return index !== i; });
        saveLevel1Photo(this.assetsObj.level1,this.photo1);
        this.save1(() => {
          list.forEach((t) => {
            localStorage.removeItem(t.item);
          })
        });
      }).catch(() => {});
    },
    delPhoto2(i) {
      this.$dialog.confirm({
        title: '删除确认',
        message: '是否确定删除该照片描述？'
      }).then(() => {
        const obj = {...this.photo2[i]};
        const list = obj.list || [];
        this.photo2 = this.photo2.filter((t,index) => { return index !== i; });
        saveLevel2Photo(this.assetsObj.level1,this.level2Index, this.photo2);
        this.save2(() => {
          list.forEach((t) => {
            localStorage.removeItem(t.item);
          })
        });
      }).catch(() => {});
    },
    iterator(i, list, index, type) {
      let _this = this;
      if (i >= list.length) {
        return;
      }
      var reader = new FileReader();
      reader.readAsDataURL(list[i].file);
      reader.onload = function() {
        compressImageCanvas(this.result, function (newSrc) {
          if (_this['photo' + type][index].list) {
            _this['photo' + type][index].list.push({src: newSrc});
          } else {
            _this.$set(_this['photo' + type][index], 'list', [{src: newSrc}]);
          }
          _this.iterator(i + 1, list, index, type);
        });
      }
    },
    afterRead1(file, obj) {
      let fileList = file instanceof Array ? file : [file];
      let index = Number(obj.name);
      // fileList = fileList.map((t) => {
      //   let src = window.URL.createObjectURL(t.file); // 浏览器关闭就会被回收清除，不能够缓存
      //   return {
      //     src,
      //   }
      // })
      // this.photo1[index].list = this.photo1[index].list.concat(fileList);
      this.iterator(0, fileList, index, 1);
    },
    afterRead2(file, obj) {
      let fileList = file instanceof Array ? file : [file];
      let index = Number(obj.name);
      // fileList = fileList.map((t) => {
      //   let src = window.URL.createObjectURL(t.file);
      //   return {
      //     src,
      //   }
      // })
      // this.photo2[index].list = this.photo2[index].list.concat(fileList);
      this.iterator(0, fileList, index, 2);
    },
    save1(callback) {
      for(let i = 0; i < this.photo1.length; i++) {
        let photoDesc = this.photo1[i];
        if (!photoDesc.label.trim()) {
          this.$toast('照片描述不能为空');
          return;
        }
        if (this.photo1.filter((t,index) => { return index > i; }).some(t => t.label.trim() === photoDesc.label.trim())) {
          this.$toast('不能保存重复的照片描述');
          return;
        }
      }
      saveLevel1Photo(this.assetsObj.level1,this.photo1);
      if (callback) {
        callback();
      }
      this.$toast.success('保存成功');
    },
    save2(callback) {
      for(let i = 0; i < this.photo2.length; i++) {
        let photoDesc = this.photo2[i];
        if (!photoDesc.label.trim()) {
          this.$toast('照片描述不能为空');
          return;
        }
        if (this.photo2.filter((t,index) => { return index > i; }).some(t => t.label.trim() === photoDesc.label.trim())) {
          this.$toast('不能保存重复的照片描述');
          return;
        }
      }
      saveLevel2Photo(this.assetsObj.level1,this.level2Index, this.photo2);
      if (callback) {
        callback();
      }
      this.$toast.success('保存成功');
    }
  }
};
</script>
<style lang="less" scoped>
.button-wrap {
  text-align: center;
  padding: 10px 0;
  .van-button {
    width: 40%;
    border-radius: 10px;
  }
}
.van-uploader {
    margin-left: 15px;
    .van-uploader__input{
      display: none;
    }
}
.van-image {
    position: relative;
    display: inline-block;
    vertical-align: top;
    .van-icon-clear{
      position: absolute;
      right: -5px;
      top: -5px;
      font-size: 20px;
    }
}
.van-image-zindex{
  z-index: 1;
}
.van-uploader__preview {
    width: 80px;
    height: 80px;
    margin: 0 10px 10px 0;
    .van-image__img{
      display: block;
    width: 100%;
    height: 100%;
    }
}
</style>
